import React, {Component} from 'react';
import {FlatList, Image, StatusBar, StyleSheet, Text, ToastAndroid, View,} from 'react-native';
import * as Color from "../../../lib.xjs/constant/Color";
import TouchableItem from "react-navigation/src/views/TouchableItem";
import BizUser from "../../entity/BizUser";
import * as BizConstant from "../../constant/BizContant";
import HttpHelper from "../../../lib.xjs/helper/HttpHelper";
import {UUID} from "../../../lib.xjs/util/UUID";
import {GaquUtil} from "../../util/GaquUtil";

const ic_avatar_default = require('../../../../img/ic_chat_audio_right.png');
const ITEM_HEIGHT = 60;

/** 仓体列表 */
export default class CabinList extends Component {

    _mFlatList;

    static navigationOptions = ({navigation}) => ({
        title: '选择舱体',
        // header: null,
    });


    constructor(props) {
        super(props);
        this.state = {
            /** 是否正在刷新 */
            mIsRefresh: false,
            /** 数据源 */
            mDatas: [],
            /** foot提示信息 */
            loadMoreInfo: '正在加载',
        };
    }

    componentDidMount(): void {
        this._getDatas(new Date(), 20, false);
    }

    render() {
        return (
            <View style={{flex: 1, backgroundColor: Color.windowWhite}}>
                <StatusBar
                    hidden={false}
                    translucent={false}
                    backgroundColor={Color.colorPrimaryDark}/>

                <FlatList
                    ref={(flatList) => this._mFlatList = flatList}
                    ListFooterComponent={this._footer()}

                    data={this.state.mDatas}
                    renderItem={(item) => this._renderItem(item)}
                    // ItemSeparatorComponent={this._separator}
                    keyExtractor={(item, index) => ("index" + index + item)}

                    refreshing={this.state.mIsRefresh}
                    onRefresh={this._onRefresh}

                    getItemLayout={this.getItemLayout}

                    onEndReachedThreshold={0.000001}
                    onEndReached={this._onReachEnd}
                />
                <HttpHelper ref={'http'}/>
            </View>
        );
    }

    /**
     * 可选优化项。但是实际测试中，如果不做该项优化，性能会差很多。
     * 所以强烈建议做此项优化！如果不做该项优化，每个列表都需要事先渲染一次，动态地取得其渲染尺寸，然后再真正地渲染到页面中。
     * 如果预先知道列表中的每一项的高度(ITEM_HEIGHT)和其在父组件中的偏移量(offset)和位置(index)，就能减少一次渲染。
     * 这是很关键的性能优化点
     * @param data
     * @param index
     * @returns {{length: number, offset: number, index: *}}
     */
    getItemLayout = (data, index) => {
        return {length: ITEM_HEIGHT, offset: (ITEM_HEIGHT + 2) * index, index}
    };

    /**
     * 将列表元素和数据结合在一起，生成列表。
     * @param item 是data属性中的每个列表的数据（ Array<object> 中的 object) 。
     */
    _renderItem = (item) => {
        return <View style={styles.item_layout_touch_bg}>
            <TouchableItem onPress={() => this._onClickItem(item)}>
                <View style={styles.item_container}>
                    <Text style={styles.text_cabin_name}>{item.item.title}</Text>

                    <View style={styles.right}>
                        <Text style={[styles.cabin_status_text, {borderColor: GaquUtil.getCabinStatusColor(item.item.status)}, {color: GaquUtil.getCabinStatusColor(item.item.status)}]}>{GaquUtil.getCabinStatusName(item.item.status)}</Text>

                        <Image style={styles.item_head}
                               source={ic_avatar_default}
                               resizeMode={Image.resizeMode.center}/>
                    </View>

                </View>
            </TouchableItem>
        </View>

    };

    /** 分割线 */
    _separator() {
        return <View style={{height: 1, backgroundColor: Color.lightGray}}/>;
    };

    /** 尾 */
    _footer() {
        return <View style={{flexDirection: 'column', backgroundColor: Color.windowWhite}}>
            <View style={{height: 0.5, backgroundColor: Color.lightMoreGray}}/>
            <Text style={[styles.txt]}>{this.state.loadMoreInfo}</Text>
        </View>;
    };

    /** 获取数据 */
    _getDatas(lastTime: Date, count: number, isClear: boolean): void {
        if (!this.refs.http) return;
        let head = BizUser.getHeadParam(true);
        let body = new Map();
        body.set("lastTime", lastTime.Format("yyyy-MM-dd hh:mm:ss"));
        body.set("count", count);
        body.set("roleId", count);

        this.refs.http.setURL(BizConstant.GET_CABIN)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("")
            .setHeadParams(head)
            .setBodyParams(body)
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                if (!res.data.cangList) return;

                // 初始化全局变量
                let datas = res.data.cangList;
                if (!isClear) datas = [...this.state.mDatas, ...datas];

                this.setState({
                    mDatas: datas,
                    loadMoreInfo: res.data.cangList.length < count ? '---已经到底了---' : '正在加载',
                });
            })
            .setTimeout(10 * 1000)
            .start(false);
    }

    /** 下拉时促发 */
    _onRefresh = () => {
        if (this.state.mIsRefresh) return;
        ToastAndroid.show('正在刷新中.... ', ToastAndroid.SHORT);
        this.setState({
            mIsRefresh: true,
        });

        let timer = setTimeout(() => {
            this.setState({
                mIsRefresh: false,
            });
            this._getDatas(new Date(), 20, true);
            clearTimeout(timer);
        }, 1000)
    };

    /** 拉到底部时促发 */
    _onReachEnd = () => {
        this._getDatas(this._getLastTimeFromList(), 20, false);
    };

    /** 跳转仓体主页 */
    _onClickItem(item): void {
        this.props.navigation.navigate('CabinExerciseList', {
            cabinName: item.item.title,            // 跳转的时候携带一个参数去下个页面
            cabinId: item.item.id,            // 跳转的时候携带一个参数去下个页面
            callback: (data) => {
            }
        })
    };

    /** 从列表中获取最晚的时间 */
    _getLastTimeFromList(): Date {
        let earistTime: Date = new Date();
        for (let item of this.state.mDatas) {
            if (!item.createTime) continue;
            let timeTarget: Date = new Date(item.createTime.replace(/-/g, "\/"));
            console.log(timeTarget);
            if (timeTarget < earistTime) earistTime = timeTarget;
        }
        return earistTime;
    }
}

const styles = StyleSheet.create({
    txt: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: Color.darkGray,
        fontSize: 14,
    },

    item_container: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: ITEM_HEIGHT,
        paddingHorizontal: 10,
    },

    item_layout_touch_bg: {
        marginHorizontal: 5,
        marginVertical: 5,
        borderRadius: 4,
        borderWidth: 0.5,
        borderColor: Color.lightMoreGray,
        backgroundColor: Color.windowWhiteLight,
    },

    text_cabin_name: {
        fontSize: 20,
    },

    text_arrow: {
        fontSize: 20,
    },

    item_head: {
        height: 30,
        width: 30,
        borderRadius: 100,
    },

    right: {
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
    },

    cabin_status_text: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 14,
        borderRadius: 4,
        borderWidth: 1,
        paddingHorizontal: 4,
    },
});
